<template>
    <view class="marketing-intro">
        <uv-navbar title="NFC营销活动" autoBack bgColor="linear-gradient(135deg, #667eea 0%, #764ba2 100%)" />
        
        <!-- 头部介绍区域 -->
        <view class="hero-section">
            <view class="hero-content">
                <view class="hero-icon">
                    <uv-icon name="scan" size="120rpx" color="#fff" />
                </view>
                <view class="hero-text">
                    <uv-text text="NFC智能营销" size="48rpx" bold color="#fff" />
                    <uv-text text="一碰即得，智能引流获客" size="28rpx" color="rgba(255,255,255,0.9)" />
                </view>
            </view>
        </view>

        <!-- 功能特点 -->
        <view class="features-section">
            <lst-title title="功能特点" bold="bold" />
            <view class="features-grid">
                <view class="feature-item" v-for="feature in features" :key="feature.title">
                    <view class="feature-icon">{{ feature.icon }}</view>
                    <uv-text :text="feature.title" size="32rpx" bold color="#333" />
                    <uv-text :text="feature.desc" size="26rpx" color="#666" />
                </view>
            </view>
        </view>

        <!-- 使用流程 -->
        <view class="process-section">
            <lst-title title="使用流程" bold="bold" />
            <view class="process-steps">
                <view class="step-item" v-for="(step, index) in processSteps" :key="index">
                    <view class="step-number">{{ index + 1 }}</view>
                    <view class="step-content">
                        <uv-text :text="step.title" size="30rpx" bold color="#333" />
                        <uv-text :text="step.desc" size="26rpx" color="#666" />
                    </view>
                </view>
            </view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-section">
            <uv-button type="primary" size="large" @click="createActivity"
                       customStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;">
                立即创建NFC活动
            </uv-button>

            <!-- 演示按钮组 -->
            <view class="demo-buttons">
                <uv-text text="体验演示" size="32rpx" bold color="#333" customStyle="margin: 30rpx 0 20rpx 0;" />

                <!-- 智能活动选择信息卡片 -->
                <view class="selected-campaign-card" v-if="selectedCampaign.campaign_id">
                    <view class="card-header">
                        <uv-icon name="scan" size="28rpx" color="#667eea" customStyle="margin-right: 8rpx;" />
                        <uv-text text="当前演示活动" size="28rpx" color="#667eea" bold />
                        <view class="status-indicator" :class="{ 'loading': campaignSelectionStatus.loading }">
                            <uv-icon v-if="!campaignSelectionStatus.loading" name="checkmark-circle" size="24rpx" color="#10B981" />
                            <uv-loading-icon v-else color="#667eea" size="24rpx" mode="spinner" />
                        </view>
                    </view>

                    <view class="card-content">
                        <view class="campaign-info">
                            <uv-text :text="selectedCampaign.campaign_name" size="26rpx" color="#333" bold />
                            <uv-text :text="`${selectedCampaign.merchant_name} • 剩余${selectedCampaign.coupon_available}张`"
                                     size="24rpx" color="#666" />
                        </view>

                        <uv-button type="default" size="mini" @click="refreshCampaignSelection"
                                   :loading="campaignSelectionStatus.loading"
                                   customStyle="height: 50rpx; padding: 0 16rpx;">
                            <uv-icon name="reload" size="20rpx" color="#667eea" customStyle="margin-right: 4rpx;" />
                            刷新
                        </uv-button>
                    </view>

                    <!-- 错误提示 -->
                    <view class="error-tip" v-if="campaignSelectionStatus.error">
                        <uv-text :text="campaignSelectionStatus.error" size="22rpx" color="#F56565" />
                    </view>

                    <!-- 最后更新时间 -->
                    <view class="update-time" v-if="campaignSelectionStatus.lastUpdateTime">
                        <uv-text :text="`更新时间: ${campaignSelectionStatus.lastUpdateTime}`" size="20rpx" color="#999" />
                    </view>
                </view>

                <uv-button type="default" size="large" @click="viewActivityDemo"
                           customStyle="margin-bottom: 20rpx;" :loading="loadingActivity">
                    <uv-icon name="scan" size="32rpx" color="#333" customStyle="margin-right: 10rpx;" />
                    <view class="button-content">
                        <view>NFC活动演示</view>
                        <view class="button-subtitle" v-if="selectedCampaign.campaign_name && selectedCampaign.coupon_available > 0">
                            {{selectedCampaign.campaign_name}} • 库存{{selectedCampaign.coupon_available}}
                        </view>
                    </view>
                </uv-button>

                <uv-button type="default" size="large" @click="viewMerchantDemo"
                           customStyle="margin-bottom: 20rpx;" :loading="loadingMerchant">
                    <uv-icon name="home-fill" size="32rpx" color="#333" customStyle="margin-right: 10rpx;" />
                    <view class="button-content">
                        <view>商户核销演示</view>
                        <view class="button-subtitle" v-if="selectedCampaign.merchant_name">
                            {{selectedCampaign.merchant_name}}
                        </view>
                    </view>
                </uv-button>

                <uv-button type="default" size="large" @click="viewUserDemo"
                           :loading="loadingUser">
                    <uv-icon name="account-fill" size="32rpx" color="#333" customStyle="margin-right: 10rpx;" />
                    <view class="button-content">
                        <view>用户中心演示</view>
                        <view class="button-subtitle" v-if="selectedCampaign.campaign_name">
                            体验{{selectedCampaign.campaign_name}}
                        </view>
                    </view>
                </uv-button>

            </view>
        </view>

        <!-- 帮助说明 -->
        <view class="help-section">
            <view class="help-card">
                <uv-text text="💡 使用提示" size="30rpx" bold color="#333" />
                <view class="help-list">
                    <view class="help-item" v-for="tip in helpTips" :key="tip">
                        <uv-text :text="'• ' + tip" size="26rpx" color="#666" />
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getNfcDemoUrls, getNfcCampaignList } from '@/api/nfc.js'

const features = ref([
    {
        icon: '📱',
        title: '一碰即得',
        desc: 'NFC设备轻触即可访问活动页面'
    },
    {
        icon: '🎯',
        title: '精准引流',
        desc: '自动关注公众号，获取用户数据'
    },
    {
        icon: '🎁',
        title: '即时奖励',
        desc: '关注后立即生成专属领奖码'
    },
    {
        icon: '📊',
        title: '数据追踪',
        desc: '完整的用户归因和效果统计'
    }
])

const processSteps = ref([
    {
        title: '创建NFC活动',
        desc: '在后台管理系统中创建营销活动'
    },
    {
        title: '生成活动链接',
        desc: '系统自动生成专属NFC活动链接'
    },
    {
        title: '配置NFC设备',
        desc: '将链接写入NFC标签或生成二维码'
    },
    {
        title: '用户扫码参与',
        desc: '用户扫码关注公众号获取奖励'
    }
])

const helpTips = ref([
    'NFC设备需要支持NFC功能的手机才能使用',
    '二维码方式适用于所有智能手机',
    '建议在活动前测试链接的有效性',
    '可以在后台查看活动参与数据统计'
])

// 加载状态
const loadingActivity = ref(false)
const loadingMerchant = ref(false)
const loadingUser = ref(false)

// 智能选择的活动信息
const selectedCampaign = ref({
    merchant_id: null,
    campaign_id: null,
    campaign_name: '',
    merchant_name: '',
    coupon_available: 0
})

// 活动选择状态
const campaignSelectionStatus = ref({
    loading: false,
    error: null,
    lastUpdateTime: null
})

const createActivity = () => {
    uni.showModal({
        title: '功能提示',
        content: '请前往后台管理系统创建NFC活动',
        showCancel: false
    })
}

// 通用的打开演示链接函数
const openDemoUrl = (url, title = '演示页面') => {
    console.log('openDemoUrl 被调用:', { url, title })

    if (!url) {
        console.error('URL为空')
        uni.showToast({
            title: '演示地址获取失败',
            icon: 'none'
        })
        return
    }

    try {
        // 在H5环境下直接使用window.open
        if (typeof window !== 'undefined' && window.open) {
            console.log('使用 window.open 打开链接:', url)
            const newWindow = window.open(url, '_blank')
            if (!newWindow) {
                console.warn('window.open 被阻止，尝试备用方案')
                // 如果被浏览器阻止，显示弹窗让用户手动打开
                uni.showModal({
                    title: title,
                    content: `请点击确定打开演示页面：${url}`,
                    showCancel: true,
                    cancelText: '复制链接',
                    confirmText: '打开页面',
                    success: (res) => {
                        if (res.confirm) {
                            // 再次尝试打开
                            window.open(url, '_blank')
                        } else if (res.cancel) {
                            // 复制链接
                            navigator.clipboard.writeText(url).then(() => {
                                uni.showToast({
                                    title: '链接已复制',
                                    icon: 'success'
                                })
                            }).catch(() => {
                                // 备用复制方案
                                uni.setClipboardData({
                                    data: url,
                                    success: () => {
                                        uni.showToast({
                                            title: '链接已复制',
                                            icon: 'success'
                                        })
                                    }
                                })
                            })
                        }
                    }
                })
            } else {
                console.log('成功打开新窗口')
            }
        } else {
            // 非H5环境或window.open不可用，显示弹窗
            console.log('非H5环境，显示弹窗')
            uni.showModal({
                title: title,
                content: url,
                showCancel: true,
                cancelText: '复制链接',
                confirmText: '确定',
                success: (res) => {
                    if (res.cancel) {
                        uni.setClipboardData({
                            data: url,
                            success: () => {
                                uni.showToast({
                                    title: '链接已复制',
                                    icon: 'success'
                                })
                            }
                        })
                    }
                }
            })
        }
    } catch (error) {
        console.error('打开演示链接失败:', error)
        uni.showToast({
            title: '打开演示页面失败',
            icon: 'none'
        })
    }
}

// 智能选择有库存的活动
const selectAvailableCampaign = async () => {
    campaignSelectionStatus.value.loading = true
    campaignSelectionStatus.value.error = null

    try {
        console.log('开始获取活动列表进行智能选择')

        // 获取启用状态的活动列表
        const response = await getNfcCampaignList({
            status: 1, // 只获取启用的活动
            available_only: true // 优先获取有库存的活动
        })

        console.log('活动列表API响应:', response)

        // 解析响应数据
        let campaignList = []
        if (response && response.data && Array.isArray(response.data.list)) {
            campaignList = response.data.list
        } else if (response && Array.isArray(response.data)) {
            campaignList = response.data
        } else if (response && Array.isArray(response)) {
            campaignList = response
        }

        console.log('解析到的活动列表:', campaignList)

        // 筛选有库存且状态正常的活动
        const toNumber = (value, defaultValue = 0) => {
            const numberValue = Number(value)
            return Number.isFinite(numberValue) ? numberValue : defaultValue
        }

        const availableCampaigns = campaignList.filter(campaign => {
            const couponAvailable = toNumber(
                campaign.coupon_available ??
                campaign.coupon_stats?.available ??
                campaign.coupon_stats?.stock
            )

            const statusValue = toNumber(campaign.status ?? campaign.status_value)
            const authorizationFlag = toNumber(
                campaign.nfc_authorization?.is_authorized ??
                campaign.nfc_authorized
            , 1)
            const enabledFlag = toNumber(
                campaign.nfc_config?.is_enabled ??
                campaign.nfc_enabled
            , 1)

            const hasStock = couponAvailable > 0
            const isActive = statusValue === 1
            const isAuthorized = authorizationFlag === 1
            const isEnabled = enabledFlag === 1

            return hasStock && isActive && isAuthorized && isEnabled
        })

        console.log('筛选后的可用活动:', availableCampaigns)

        if (availableCampaigns.length > 0) {
            // 按库存数量排序，选择库存最多的活动
            availableCampaigns.sort((a, b) => {
                const stockA = toNumber(
                    a.coupon_available ??
                    a.coupon_stats?.available ??
                    a.coupon_stats?.stock
                )
                const stockB = toNumber(
                    b.coupon_available ??
                    b.coupon_stats?.available ??
                    b.coupon_stats?.stock
                )

                return stockB - stockA
            })
            const bestCampaign = availableCampaigns[0]
            const couponAvailable = toNumber(
                bestCampaign.coupon_available ??
                bestCampaign.coupon_stats?.available ??
                bestCampaign.coupon_stats?.stock
            )

            // 更新选中的活动信息
            selectedCampaign.value = {
                merchant_id: bestCampaign.merchant_id,
                campaign_id: bestCampaign.id ?? bestCampaign.campaign_id,
                campaign_name: bestCampaign.campaign_name || '未命名活动',
                merchant_name: bestCampaign.merchant_name || '未知商户',
                coupon_available: couponAvailable
            }

            campaignSelectionStatus.value.lastUpdateTime = new Date().toLocaleString()

            console.log('智能选择的活动:', selectedCampaign.value)

            return {
                success: true,
                campaign: selectedCampaign.value
            }
        } else {
            // 没有找到可用的活动
            campaignSelectionStatus.value.error = '暂无可用的演示活动'

            // 回退到默认活动
            selectedCampaign.value = {
                merchant_id: 5,
                campaign_id: 11,
                campaign_name: '默认演示活动',
                merchant_name: '演示商户',
                coupon_available: 0
            }

            return {
                success: false,
                message: '暂无有库存的活动，使用默认演示活动',
                campaign: selectedCampaign.value
            }
        }

    } catch (error) {
        console.error('智能选择活动失败:', error)
        campaignSelectionStatus.value.error = '获取活动列表失败'

        // 回退到默认活动
        selectedCampaign.value = {
            merchant_id: 5,
            campaign_id: 11,
            campaign_name: '默认演示活动',
            merchant_name: '演示商户',
            coupon_available: 0
        }

        return {
            success: false,
            message: '网络错误，使用默认演示活动',
            campaign: selectedCampaign.value
        }
    } finally {
        campaignSelectionStatus.value.loading = false
    }
}

// 获取演示地址配置
const getDemoUrls = async () => {
    try {
        console.log('开始获取演示地址配置')

        // 先智能选择有库存的活动
        const selectionResult = await selectAvailableCampaign()

        if (!selectionResult.success && selectionResult.message) {
            // 显示选择结果提示
            uni.showToast({
                title: selectionResult.message,
                icon: 'none',
                duration: 3000
            })
        }

        const { merchant_id, campaign_id } = selectedCampaign.value

        console.log(`使用活动进行演示: 商户${merchant_id}, 活动${campaign_id}, 库存${selectedCampaign.value.coupon_available}`)

        const response = await getNfcDemoUrls({
            merchant_id,
            campaign_id
        })
        console.log('API响应:', response)

        // 根据响应拦截器的逻辑，成功的响应会直接返回data对象
        // 检查响应格式 - 可能是 response.data 或直接是 response
        let demoData = null
        if (response && response.data) {
            // 如果响应有data属性，使用response.data
            demoData = response.data
        } else if (response && (response.nfc_activity || response.merchant_verify || response.user_center)) {
            // 如果响应直接包含演示数据，直接使用response
            demoData = response
        }

        if (demoData) {
            console.log('演示地址数据:', demoData)
            return demoData
        } else {
            console.error('API响应格式不正确:', response)
            return null
        }
    } catch (error) {
        console.error('获取演示地址配置失败:', error)
        uni.showToast({
            title: '获取演示地址失败',
            icon: 'none'
        })
        return null
    }
}

// NFC活动演示
const viewActivityDemo = async () => {
    console.log('viewActivityDemo 被调用')
    loadingActivity.value = true
    try {
        const demoUrls = await getDemoUrls()
        console.log('获取到的演示地址:', demoUrls)
        if (demoUrls && demoUrls.nfc_activity) {
            console.log('准备打开NFC活动演示:', demoUrls.nfc_activity)
            openDemoUrl(demoUrls.nfc_activity.url, demoUrls.nfc_activity.title)
        } else {
            console.error('未找到NFC活动演示配置')
            uni.showToast({
                title: '未找到演示配置',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('获取NFC活动演示地址失败:', error)
    } finally {
        loadingActivity.value = false
    }
}

// 商户核销演示
const viewMerchantDemo = async () => {
    console.log('viewMerchantDemo 被调用')
    loadingMerchant.value = true
    try {
        const demoUrls = await getDemoUrls()
        console.log('获取到的演示地址:', demoUrls)
        if (demoUrls && demoUrls.merchant_verify) {
            console.log('准备打开商户核销演示:', demoUrls.merchant_verify)
            openDemoUrl(demoUrls.merchant_verify.url, demoUrls.merchant_verify.title)
        } else {
            console.error('未找到商户核销演示配置')
            uni.showToast({
                title: '未找到演示配置',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('获取商户核销演示地址失败:', error)
    } finally {
        loadingMerchant.value = false
    }
}

// 用户中心演示
const viewUserDemo = async () => {
    console.log('viewUserDemo 被调用')
    loadingUser.value = true
    try {
        const demoUrls = await getDemoUrls()
        console.log('获取到的演示地址:', demoUrls)
        if (demoUrls && demoUrls.user_center) {
            console.log('准备打开用户中心演示:', demoUrls.user_center)
            openDemoUrl(demoUrls.user_center.url, demoUrls.user_center.title)
        } else {
            console.error('未找到用户中心演示配置')
            uni.showToast({
                title: '未找到演示配置',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('获取用户中心演示地址失败:', error)
    } finally {
        loadingUser.value = false
    }
}

// 刷新活动选择
const refreshCampaignSelection = async () => {
    try {
        const result = await selectAvailableCampaign()
        if (result.success) {
            uni.showToast({
                title: `已选择活动: ${selectedCampaign.value.campaign_name}`,
                icon: 'success',
                duration: 2000
            })
        } else {
            uni.showToast({
                title: result.message || '刷新失败',
                icon: 'none',
                duration: 3000
            })
        }
    } catch (error) {
        uni.showToast({
            title: '刷新失败，请重试',
            icon: 'error'
        })
    }
}

// 页面初始化时自动选择活动
onMounted(async () => {
    console.log('NFC营销演示页面初始化，开始智能选择活动')

    try {
        const result = await selectAvailableCampaign()
        if (result.success) {
            console.log('页面初始化时成功选择活动:', selectedCampaign.value)
        } else {
            console.log('页面初始化时活动选择失败，使用默认活动:', result.message)
        }
    } catch (error) {
        console.error('页面初始化时活动选择出错:', error)
    }
})
</script>

<style lang="scss" scoped>
.marketing-intro {
    background: #f5f5f5;
    min-height: 100vh;
}

.hero-section {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 60rpx 40rpx;
    
    .hero-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-align: center;
        
        .hero-icon {
            margin-bottom: 40rpx;
        }
        
        .hero-text {
            display: flex;
            flex-direction: column;
            gap: 20rpx;
        }
    }
}

.features-section, .process-section {
    padding: 40rpx;
    
    .features-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 30rpx;
        margin-top: 30rpx;
        
        .feature-item {
            background: #fff;
            padding: 40rpx 30rpx;
            border-radius: 20rpx;
            text-align: center;
            box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
            
            .feature-icon {
                font-size: 60rpx;
                margin-bottom: 20rpx;
            }
        }
    }
    
    .process-steps {
        margin-top: 30rpx;
        
        .step-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 40rpx;
            
            .step-number {
                width: 60rpx;
                height: 60rpx;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: #fff;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: bold;
                margin-right: 30rpx;
                flex-shrink: 0;
            }
            
            .step-content {
                flex: 1;
                display: flex;
                flex-direction: column;
                gap: 10rpx;
            }
        }
    }
    
}

.action-section {
    padding: 40rpx;

    .demo-buttons {
        margin-top: 40rpx;

        .uv-button {
            display: flex;
            align-items: center;
            justify-content: center;

            .button-content {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 4rpx;

                .button-subtitle {
                    font-size: 22rpx;
                    color: #999;
                    line-height: 1.2;
                    max-width: 300rpx;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }
        }

        // 智能活动选择信息卡片样式
        .selected-campaign-card {
            background: #fff;
            border-radius: 20rpx;
            padding: 30rpx;
            margin-bottom: 30rpx;
            box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.1);
            border: 2rpx solid #f0f4ff;

            .card-header {
                display: flex;
                align-items: center;
                margin-bottom: 20rpx;

                .status-indicator {
                    margin-left: auto;

                    &.loading {
                        animation: pulse 1.5s infinite;
                    }
                }
            }

            .card-content {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 16rpx;

                .campaign-info {
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    gap: 8rpx;
                }
            }

            .error-tip {
                background: #FEF2F2;
                padding: 12rpx 16rpx;
                border-radius: 12rpx;
                margin-bottom: 12rpx;
                border-left: 4rpx solid #F56565;
            }

            .update-time {
                display: flex;
                justify-content: flex-end;
                margin-top: 8rpx;
            }
        }

        @keyframes pulse {
            0%, 100% {
                opacity: 1;
            }
            50% {
                opacity: 0.5;
            }
        }
    }
}

.help-section {
    padding: 40rpx;
    
    .help-card {
        background: #fff;
        padding: 40rpx;
        border-radius: 20rpx;
        box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
        
        .help-list {
            margin-top: 30rpx;
            
            .help-item {
                margin-bottom: 20rpx;
            }
        }
    }
}
</style>
